export function parse(url) {
  url = url == null ? window.location.href : url
  const search = url.includes('?')
    ? url.substring(url.lastIndexOf('?') + 1)
    : null
  if (!search) {
    return {}
  }
  return JSON.parse(
    `{"${decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')}"}`
  )
}

export function stringify(obj) {
  if (!obj) return ''
  const pairs = []
  for (const key in obj) {
    const value = obj[key]
    if (value instanceof Array) {
      for (let i = 0; i < value.length; ++i) {
        const key = encodeURIComponent(`${key}[${i}]`)
        const value = encodeURIComponent(value[i])
        pairs.push(`${key}=${value}`)
      }
      continue
    }
    pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
  }
  return pairs.join('&')
}

export default {
  parse,
  stringify
}
